package com.lyfam.game.geometry;

import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;

import com.lyfam.game.entity.MovingEntity;

import processing.core.PGraphics;

public class CommonGeometry
{

	private static AffineTransform affine = new AffineTransform();

	/**
	 * Convert the a vector from world coordinate to the local coordinate. The
	 * local coordinate is preset within the {@link PGraphics} g object. The
	 * arithmetic is using the affine transform.
	 * 
	 * @param g
	 *            {@link PGraphics} object
	 * @param v
	 *            The vector to convert {@link Vector2D}
	 * @return The {@link Vector2D} in the current local coordinate
	 */
	public static Vector2D ConvertFromWorldToLocal(MovingEntity local, Vector2D v)
	{
		Vector2D result = new Vector2D();

		float xPos = local.getPosition().getX();
		float yPos = local.getPosition().getY();
		float theta = local.getVelocity().heading2D();

		try
		{
			// set the current transform of local coordinate
			affine.setTransform(Math.cos(theta), Math.sin(theta), -Math.sin(theta), Math.cos(theta), xPos, yPos);
			// creating the inverse from world to local
			Point2D p = affine.inverseTransform(new Point2D.Float(v.getX(), v.getY()), null);
			result.setX((float) p.getX());
			result.setY((float) p.getY());
		}
		catch (NoninvertibleTransformException e)
		{
			e.printStackTrace();
		}

		return result;
	}
}
